/*
 * All content copyright http://www.j2eefast.com, unless
 * otherwise indicated. All rights reserved.
 * No deletion without permission
 */
package com.j2eefast.web.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.j2eefast.web.common.BaseUrl;
import com.j2eefast.web.entity.ItemSkuPriceEntity;
import com.j2eefast.web.entity.ItemSkuPropEntity;
import com.j2eefast.web.entity.SkuEntity;
import com.j2eefast.web.mapper.ItemSkuPriceMapper;
import com.j2eefast.web.mapper.ItemSkuPropMapper;
import com.j2eefast.web.mapper.SkuMapper;
import com.j2eefast.common.core.page.Query;
import com.j2eefast.common.core.utils.PageUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.j2eefast.common.core.utils.ToolUtil;
import com.j2eefast.framework.utils.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import javax.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;
import java.util.List;
import java.util.Arrays;

/**
 * 【请填写功能名称】Service接口
 * @author: ZhouZhou
 * @date 2021-06-11 10:29:56
 */
@Service
public class SkuService extends ServiceImpl<SkuMapper,SkuEntity> {

	@Resource
	private SkuMapper skuMapper;
	
	@Autowired
	private ItemSkuPriceService skuPriceService;

	@Autowired
	private ItemSkuPropService skuPropService;

	/**
	 * 保存SKU数据
	 *
	 * @param itemSkus
	 */
	public void saveSkuData(JSONArray itemSkus, String token) {
		if (itemSkus == null || itemSkus.size() == 0) {
			return;
		}

		for (int i = 0; i < itemSkus.size(); i++) {

			JSONObject skuJson = itemSkus.getJSONObject(i);
			Long skuId = skuJson.getLong("id");

			String url = "";
			String detailUrl = "";
			String typeCode = skuJson.getStr("typeCode");
			if ("1".equals(typeCode) || "4".equals(typeCode)) {
				url = String.format(BaseUrl.ITEM_SKU_DETAIL, skuId);
				detailUrl = String.format(BaseUrl.PAGE_ITEM_SKU_DETAIL, skuId);
			} else if ("3".equals(typeCode)) {
				url = String.format(BaseUrl.SUPER_ITEM_SKU_DETAIL, skuId);
				detailUrl = String.format(BaseUrl.PAGE_SUPER_ITEM_SKU_DETAIL, skuId);
			} else if (StrUtil.isEmpty(url)) {
				System.out.println(skuJson);
			}
			String res = HttpRequest.get(url).header("X-AIYANGNIU-SIGNATURE", token)
					.execute().body();

			JSONObject data = JSONUtil.parseObj(res);

			SkuEntity s = getData(data.getJSONObject("data"));

			s.setDetailUrl(detailUrl);
			SkuEntity query = new SkuEntity();
			query.setId(s.getId());
			List<SkuEntity> dataList = skuMapper.findList(query);
			if (dataList != null && dataList.size() > 0) {
				s.setPkId(dataList.get(0).getPkId());
			}
			this.saveOrUpdate(s);
		}
	}

	private SkuEntity getData(JSONObject data) {
		SkuEntity s = new SkuEntity();
		s.setAccountPeriod(data.getInt("accountPeriod"));
		s.setAddTime(data.getLong("addTime"));
		s.setCollected(data.getBool("collected"));
		s.setDeleted(data.getStr("deleted"));
		s.setId(data.getLong("id"));
		JSONArray images = data.getJSONArray("images");
		s.setImages("");
		if (images != null && images.size() > 0) {
			s.setImages(Joiner.on(",").join(images));
		}

		s.setImgsCover(data.getStr("imgsCover"));
		s.setIsDeliver(data.getInt("isDeliver"));
		s.setIsGiftPack(data.getInt("isGiftPack"));
		s.setIsNational(data.getStr("isNational"));
		s.setIsPickUp(data.getInt("isPickUp"));

		JSONArray itemPrices = data.getJSONArray("itemPrices");
		if (itemPrices != null && itemPrices.size() > 0) {
			List<ItemSkuPriceEntity> priceList = Lists.newArrayListWithCapacity(itemPrices.size());
			ItemSkuPriceEntity query = new ItemSkuPriceEntity();
			for (int i = 0; i < itemPrices.size(); i++) {
				JSONObject itemPrice = itemPrices.getJSONObject(i);
				ItemSkuPriceEntity price = new ItemSkuPriceEntity();
				price.setId(itemPrice.getLong("id"));
				price.setItemSkuId(itemPrice.getLong("itemSkuId"));
				price.setPrice(itemPrice.getBigDecimal("price"));
				price.setPriceName(itemPrice.getStr("priceName"));
				price.setTypeCode(itemPrice.getInt("typeCode"));

				query.setId(price.getId());
				List<ItemSkuPriceEntity> dataList = skuPriceService.findList(query);
				if (dataList != null && dataList.size() > 0) {
					price.setPkId(dataList.get(0).getPkId());
				}
				priceList.add(price);
			}
			skuPriceService.saveOrUpdateBatch(priceList);
		}

		JSONArray itemSkuProps = data.getJSONArray("itemSkuProps");
		if (itemSkuProps != null && itemSkuProps.size() > 0) {
			List<ItemSkuPropEntity> itemSkuPropList = Lists.newArrayListWithCapacity(itemSkuProps.size());
			ItemSkuPropEntity query = new ItemSkuPropEntity();
			for (int i = 0; i < itemSkuProps.size(); i++) {
				JSONObject itemSkuProp = itemSkuProps.getJSONObject(i);
				ItemSkuPropEntity skuProp = new ItemSkuPropEntity();
				skuProp.setAddTime(itemSkuProp.getLong("addTime"));
				skuProp.setDeleted(itemSkuProp.getStr("deleted"));
				skuProp.setId(itemSkuProp.getLong("id"));
				skuProp.setIsSearch(itemSkuProp.getInt("isSearch"));
				skuProp.setPropId(itemSkuProp.getLong("propId"));
				skuProp.setPropName(itemSkuProp.getStr("propName"));
				skuProp.setPropValue(itemSkuProp.getStr("propValue"));
				skuProp.setSkuId(itemSkuProp.getLong("skuId"));


				query.setId(skuProp.getId());
				List<ItemSkuPropEntity> dataList = skuPropService.findList(query);
				if (dataList != null && dataList.size() > 0) {
					skuProp.setPkId(dataList.get(0).getPkId());
				}

				itemSkuPropList.add(skuProp);
			}

			skuPropService.saveOrUpdateBatch(itemSkuPropList);
		}

		s.setItemStock(data.getBigDecimal("itemStock"));
		s.setMengniuPay(data.getInt("mengniuPay"));
		s.setMinQuantity(data.getBigDecimal("minQuantity"));
		s.setOfflinePay(data.getInt("offlinePay"));
		s.setOffSaleReason(data.getStr("offSaleReason"));
		s.setOffSaleStatus(data.getInt("offSaleStatus"));
		s.setOldPrice(data.getBigDecimal("oldPrice"));
		s.setPrice(data.getBigDecimal("price"));
		s.setPriceLabel(data.getStr("priceLabel"));
		s.setPriceSystem(data.getStr("priceSystem"));
		s.setSettlementPrice(data.getBigDecimal("settlementPrice"));
		s.setSkuStatus(data.getInt("skuStatus"));
		s.setSpuId(data.getLong("spuId"));
		s.setStockCountMode(data.getInt("stockCountMode"));
		s.setTypeCode(data.getStr("typeCode"));
		s.setUnit(data.getStr("unit"));
		s.setUpdateTime(data.getLong("updateTime"));
		s.setVersion(data.getStr("version"));
		s.setRemark(data.getStr("remark"));

		JSONObject itemSkuSummary = data.getJSONObject("itemSkuSummary");
		if (itemSkuSummary != null) {
			s.setSkuComments(itemSkuSummary.getLong("skuComments"));
			s.setSkuVisits(itemSkuSummary.getLong("skuVisits"));
			s.setSkuSales(itemSkuSummary.getLong("skuSales"));
		}

		return s;
	}

	/**
	 * mybaitis-plus 单表页面分页查询
     */
	public PageUtil findPage(Map<String, Object> params) {
		QueryWrapper<SkuEntity> queryWrapper = new QueryWrapper<SkuEntity>();
		String accountPeriod = (String) params.get("accountPeriod");
        queryWrapper.eq(ToolUtil.isNotEmpty(accountPeriod), "account_period", accountPeriod);
		String addTime = (String) params.get("addTime");
        queryWrapper.eq(ToolUtil.isNotEmpty(addTime), "add_time", addTime);
		String collected = (String) params.get("collected");
        queryWrapper.eq(ToolUtil.isNotEmpty(collected), "collected", collected);
		String deleted = (String) params.get("deleted");
        queryWrapper.eq(ToolUtil.isNotEmpty(deleted), "deleted", deleted);
		String images = (String) params.get("images");
        queryWrapper.eq(ToolUtil.isNotEmpty(images), "images", images);
		String imgsCover = (String) params.get("imgsCover");
        queryWrapper.eq(ToolUtil.isNotEmpty(imgsCover), "imgs_cover", imgsCover);
		String isDeliver = (String) params.get("isDeliver");
        queryWrapper.eq(ToolUtil.isNotEmpty(isDeliver), "is_deliver", isDeliver);
		String isGiftPack = (String) params.get("isGiftPack");
        queryWrapper.eq(ToolUtil.isNotEmpty(isGiftPack), "is_gift_pack", isGiftPack);
		String isNational = (String) params.get("isNational");
        queryWrapper.eq(ToolUtil.isNotEmpty(isNational), "is_national", isNational);
		String isPickUp = (String) params.get("isPickUp");
        queryWrapper.eq(ToolUtil.isNotEmpty(isPickUp), "is_pick_up", isPickUp);
		String itemStock = (String) params.get("itemStock");
        queryWrapper.eq(ToolUtil.isNotEmpty(itemStock), "item_stock", itemStock);
		String mengniuPay = (String) params.get("mengniuPay");
        queryWrapper.eq(ToolUtil.isNotEmpty(mengniuPay), "mengniu_pay", mengniuPay);
		String minQuantity = (String) params.get("minQuantity");
        queryWrapper.eq(ToolUtil.isNotEmpty(minQuantity), "min_quantity", minQuantity);
		String offSaleReason = (String) params.get("offSaleReason");
        queryWrapper.eq(ToolUtil.isNotEmpty(offSaleReason), "off_sale_reason", offSaleReason);
		String offSaleStatus = (String) params.get("offSaleStatus");
        queryWrapper.eq(ToolUtil.isNotEmpty(offSaleStatus), "off_sale_status", offSaleStatus);
		String offlinePay = (String) params.get("offlinePay");
        queryWrapper.eq(ToolUtil.isNotEmpty(offlinePay), "offline_pay", offlinePay);
		String oldPrice = (String) params.get("oldPrice");
        queryWrapper.eq(ToolUtil.isNotEmpty(oldPrice), "old_price", oldPrice);
		String price = (String) params.get("price");
        queryWrapper.eq(ToolUtil.isNotEmpty(price), "price", price);
		String priceLabel = (String) params.get("priceLabel");
        queryWrapper.eq(ToolUtil.isNotEmpty(priceLabel), "price_label", priceLabel);
		String priceSystem = (String) params.get("priceSystem");
        queryWrapper.eq(ToolUtil.isNotEmpty(priceSystem), "price_system", priceSystem);
		String settlementPrice = (String) params.get("settlementPrice");
        queryWrapper.eq(ToolUtil.isNotEmpty(settlementPrice), "settlement_price", settlementPrice);
		String skuStatus = (String) params.get("skuStatus");
        queryWrapper.eq(ToolUtil.isNotEmpty(skuStatus), "sku_status", skuStatus);
		String spuId = (String) params.get("spuId");
        queryWrapper.eq(ToolUtil.isNotEmpty(spuId), "spu_id", spuId);
		String stockCountMode = (String) params.get("stockCountMode");
        queryWrapper.eq(ToolUtil.isNotEmpty(stockCountMode), "stock_count_mode", stockCountMode);
		String typeCode = (String) params.get("typeCode");
        queryWrapper.eq(ToolUtil.isNotEmpty(typeCode), "type_code", typeCode);
		String unit = (String) params.get("unit");
        queryWrapper.eq(ToolUtil.isNotEmpty(unit), "unit", unit);
		String version = (String) params.get("version");
        queryWrapper.eq(ToolUtil.isNotEmpty(version), "version", version);
		String detailUrl = (String) params.get("detailUrl");
        queryWrapper.eq(ToolUtil.isNotEmpty(detailUrl), "detail_url", detailUrl);
		String skuComments = (String) params.get("skuComments");
        queryWrapper.eq(ToolUtil.isNotEmpty(skuComments), "sku_comments", skuComments);
		String skuSales = (String) params.get("skuSales");
        queryWrapper.eq(ToolUtil.isNotEmpty(skuSales), "sku_sales", skuSales);
		String skuVisits = (String) params.get("skuVisits");
        queryWrapper.eq(ToolUtil.isNotEmpty(skuVisits), "sku_visits", skuVisits);
		Page<SkuEntity> page = skuMapper.selectPage(new Query<SkuEntity>(params).getPage(), queryWrapper);
		return new PageUtil(page);
    }

	/**
	 * 自定义分页查询，含关联实体对像
	 */
	public PageUtil findPage(Map<String, Object> params,SkuEntity skuEntity) {
		Page<SkuEntity> page = skuMapper.findPage(new Query<SkuEntity>(params).getPage(),
					skuEntity,
				(String) params.get(Constant.SQL_FILTER));
		return new PageUtil(page);
	}

	/**
	* 查列表
	*/
	public List<SkuEntity> findList(SkuEntity skuEntity){
		return skuMapper.findList(skuEntity);
	}

	/**
     * 批量删除
     */
	@Transactional(rollbackFor = Exception.class)
	public boolean deleteBatchByIds(Long[] ids) {
		return this.removeByIds(Arrays.asList(ids));
	}

	/**
     * 单个删除
     */
	@Transactional(rollbackFor = Exception.class)
	public boolean delSkuById(Long pkId) {
		return this.removeById(pkId);
	}

	/**
     * 保存
     */
	@Transactional(rollbackFor = Exception.class)
	public boolean addSku(SkuEntity sku){
		if(this.save(sku)){
			return true;
		}
        return false;
    }

	/**
     * 修改根居ID
     */
	@Transactional(rollbackFor = Exception.class)
	public boolean updateSkuById(SkuEntity sku) {
		if(this.updateById(sku)){
			return true;
		}
		return false;
	}

	/**
     * 根居ID获取对象
     */
	public SkuEntity findSkuById(Long pkId){
		return skuMapper.findSkuById(pkId);
	}


}
